﻿package tk.mystudio.web.action;

import org.apache.commons.lang.xwork.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import tk.mystudio.permission.bean.Account;
import tk.mystudio.permission.constant.AccountState;
import tk.mystudio.permission.exception.AccountNotExistException;
import tk.mystudio.permission.service.AccountService;

import com.opensymphony.xwork2.ActionContext;

public class LoginManagerAction {
	
	private Logger logger = LoggerFactory.getLogger(LoginManagerAction.class);

	private String name;
	private String password;
	
	private AccountService accountService;
	
	public String index() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if(auth!=null && auth.getClass()!=AnonymousAuthenticationToken.class) {
			return "index";
		}
		return "login";
	}
	
	public String login() {
		if(StringUtils.isBlank(name)) {
			return "login";
		}
		if(StringUtils.isBlank(password)) {
			return "login";
		}
		Account account = null;
		try {
			account = accountService.getAccountByName(name);
		} catch (AccountNotExistException e) {
			return "login";
		}
		if(account.getState()==AccountState.LOCKED) {
			return "login";
		} else if(account.getState()==AccountState.DISABLED) {
			return "login";
		}
		String pwd = new Md5PasswordEncoder().encodePassword(password, name);
		if(!account.getPassword().equals(pwd)) {
			logger.info("xxxxxx error password:{}-{}", pwd, account.getPassword());
			return "login";
		}
		ActionContext.getContext().getSession().put("account", account);
		return "index";
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}
	
}
